package com.zzyl.nursing.service.impl;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.AIModelInvoker;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.nursing.vo.HealthReportVo;
import com.zzyl.nursing.vo.RiskDistributionVo;
import io.swagger.util.Json;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 *
 * @author success
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AIModelInvoker AIModelInvoker;

    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessment healthAssessment) {
        // 1.组装prompt
        String prompt = getPrompt(healthAssessment);

        // 2.调用千帆大模型来分析数据
        String qianfanResult = AIModelInvoker.qianfanInvoker(prompt);

        // 3.将数据保存到数据库中,并返回
        //将大模型返回的字符串转换为对象，方便取数据
        HealthReportVo healthReportVo = JSONUtil.toBean(qianfanResult, HealthReportVo.class);

        return saveHealthAssessment(healthReportVo, healthAssessment);
    }

    /**
     * 保存健康评估数据
     *
     * @param healthAssessment
     * @param
     * @return
     */
    private Long saveHealthAssessment(HealthReportVo healthReportVo, HealthAssessment healthAssessment) {

        //获取身份证
        String idCard = healthAssessment.getIdCard();
        LocalDateTime birthDate = IDCardUtils.getBirthDateByIdCard(idCard);
        healthAssessment.setBirthDate(birthDate);
        int age = IDCardUtils.getAgeByIdCard(idCard);
        healthAssessment.setAge(age);
        int gender = IDCardUtils.getGenderFromIdCard(idCard);
        healthAssessment.setGender(gender);

        //健康评分
        double healthScore = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthScore));

        //健康等级
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());

        //是否建议入住
        healthAssessment.setSuggestionForAdmission(healthScore > 60 ? 0 : 1);

        //推荐护理等级
        String nursingLevelName = getLevelNameByHealthIndex(healthScore);
        healthAssessment.setNursingLevelName(nursingLevelName);

        //入住情况
        healthAssessment.setAdmissionStatus(1);

        //总检日期
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());

        //评估时间
        healthAssessment.setAssessmentTime(LocalDateTime.now());

        //报告总结
        healthAssessment.setReportSummary(healthReportVo.getSummarize());

        //疾病风险
        healthAssessment.setRiskLevel(JSON.toJSONString(healthReportVo.getRiskDistribution()));

        //异常分析
        healthAssessment.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData()));

        //八大系统分值
        healthAssessment.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore()));

        healthAssessmentMapper.insert(healthAssessment);
        return healthAssessment.getId();
    }

    /**
     * 根据健康指数获取护理等级
     *
     * @param healthScore
     * @return
     */
    private String getLevelNameByHealthIndex(double healthScore) {
        if (healthScore > 100 || healthScore < 0) {
            throw new BaseException("健康指数不合法！");
        }

        if (healthScore >= 60 && healthScore < 70) {
            return "三级护理等级";
        } else if (healthScore >= 70 && healthScore < 80) {
            return "二级护理等级";
        } else if (healthScore >= 80 && healthScore < 90) {
            return "一级护理等级";
        } else if (healthScore >= 90) {
            return "特级护理等级";
        }
        return "无";
    }

    /**
     * 组装prompt
     *
     * @param healthAssessment
     * @return
     */
    public String getPrompt(HealthAssessment healthAssessment) {

        try (
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("prompts\\healthReport.txt");
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        ) {
            //获取缓存中的pdf文件
            String content = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT_KEY, healthAssessment.getIdCard());

            //删除缓存中的pdf文件
            redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT_KEY, healthAssessment.getIdCard());

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
                if (line.contains("体检内容如下：")) {
                    sb.append(content);
                }
            }
            return sb.toString();
        } catch (IOException e) {
            throw new BaseException("读取文件获取提示词失败！");
        }
    }

    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return healthAssessmentMapper.deleteById(id);
    }
}
